//用户管理

/**
 * 用户详情视图模型
 */
interface IUserManagentDetailViewModel {
    /**
     * 用户编号
     */
    id?: string;
    /**
     * 用户名
     */
    userNameBox: string;
    /**
     * 密码
     */
    password: string;
    /**
     * 重复密码
     */
    rePassword: string;
    /**
     * 邮箱
     */
    email: string;
    /**
     * 手机号
     */
    phoneNumberBox: string;
    /**
     * 是否启用
     */
    isEnabledBox: boolean;
    /**
     * 所属用户组
     */
    userGroupId: string;
    /**
     * 密码缺省提示
     */
    passwordTitle: string;
    /**
     * 权限值
     */
    roles: { role: string[] };
    /**
     * 添加/编辑中确定按钮事件
     */
    click: () => void;
    /**
     * 监听用户组下拉选中事件并自动勾选对应的权限
     */
    userGroupSelected: () => void;
    /**
     * 用户输入框是否禁用
     */
    nameDisable: boolean;

    highAuthNumber?:string;

    middleAuthNumber?:string;

    lowAuthNumber?:string;
    secAuthorizationTypeTag?:string[]
    
}

/**
 * 用户视图模型
 */
interface IUserManagentViewModel extends IBaseViewModel<IUserManagentQueryTerms> {
    /**
     * 用户组下拉数据
     */
    userGroupList: UserGroupListItemResponse[];
    
    /**
     * 编辑用户时，特定物流公司下的用户组下拉数据
     */
    userGroupList2:UserGroupListItemResponse[];
    /**
     * 用户列表组件配置信息
     */
    gridOptions: uiGrid.IGridOptionsOf<UserListItemResponse>;
    /**
     * 用户添加/编辑视图模型
     */
    detail: IUserManagentDetailViewModel;
    // /**
    //  * 添加用户
    //  */
    // addUser: () => void;
    /**
     * 编辑用户
     */
    editUser: (id: string) => void;
    /**
     * 查询
     */
    query: () => void;
    /**
     * 列表高度
     */
    heightA: number;
    //权限列表
    authTree: ListResponse<visualAuthorizationListItemReponse>

    /**
    * 折叠h或者展开树
    */
    toggleTree: () => void
    /**
    * 树的展开状态
    */
    treeExpand: boolean;

    authNumbers: { high: number[], middle: number[], low: number[] }
    secAuthTypeTag: string[]

    saveChecked: number;

    saveCheckedAuth: () => void;
    /**
     * 编辑用户组权限
     */
    editUserAuthorization: (any) => void;
    /**
     * 选中用户组的名称
     */
    UserName: string;
}

/**
 * 查询条件
 */
interface IUserManagentQueryTerms {
    /**
     * 用户名
     */
    userName: string;
    /**
     * 手机号
     */
    phoneNumber: string;
    /**
     * 是否启用
     */
    isEnabled: boolean;
    /**
     * 用户组编号
     */
    userGroupId: string;
}

class UserManagentController extends ListController<IUserManagentViewModel, IUserManagentQueryTerms> {
    gridApi: uiGrid.IGridApiOf<UserListItemResponse>;
    selectedRow: any;
    constructor($scope: IUserManagentViewModel, private userService: IUserService,
        private userGroupService: IUserGroupService, private $ngBootbox: BootboxService, private visualAuthorizationService: visualAuthorizationService) {
        super($scope);
        this.init();
    }

    /**
     * 初始化
     */
    init(): void {
        super.init();
        // this.$scope.addUser = this.showAddUserDialog;
        this.$scope.editUser = this.showEditUserDialog;
        this.$scope.editUserAuthorization = this.editUserAuthorization;
        this.$scope.queryTerms = {
            userName: "",
            phoneNumber: "",
            isEnabled: null,
            userGroupId: ""
        };
        this.$scope.toggleTree = () => {
            this.$scope.treeExpand = !this.$scope.treeExpand
        }

        this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10, 20, 30],
            columnDefs: [
                { name: "序号", field: "index", enableColumnMenu: false },
                { name: "用户名", field: "userName", enableColumnMenu: false },
                { name: "所属系统", field: "systemType", enableColumnMenu: false },
                { name: "手机号", field: "phoneNumber", enableColumnMenu: false },
                { name: "用户组", field: "userGroup", enableColumnMenu: false },
                { name: "创建时间", field: "createTime", enableColumnMenu: false },
                { name: "最后登录时间", field: "lastLoginTime", enableColumnMenu: false },
                { name: "是否启用", cellTemplate: '<span class="m-l-xs" ng-show="row.entity.isEnabled">是</span> <span class="m-l-xs" ng-hide="row.entity.isEnabled">否</span>', enableColumnMenu: false },
                {
                    name: "操作",
                    cellFilter: 'checkmark',
                    cellTemplate: '<a data-toggle="modal" title="编辑" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" ng-click="grid.appScope.editUser(row.entity)"></a> <a data-toggle="modal" data-target="#authModal" ng-if="row.entity.systemType==\'TMS\'" class="fa fa-pencil-square m-l-xs m-r-xs primary text-info" title="权限编辑" ng-click="grid.appScope.editUserAuthorization(row.entity)"></a>',
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };
        this.$scope.query = this.query;
        this.query();
        this.loadUserGroupDropDown();
        this.$scope.authNumbers = {
            high: [],
            middle: [],
            low: []
        }

        this.$scope.secAuthTypeTag = [];
        this.$scope.UserName = '';
        this.$scope.saveChecked = 0
        this.$scope.saveCheckedAuth = this.saveCheckedAuth;
    }

    /**
     * 加载用户组下拉数据
     */
    loadUserGroupDropDown(logisticsCompanyId?:string): void {
        if(logisticsCompanyId){
            this.userGroupService.getList("", 0, -1,logisticsCompanyId).then(result => {
                this.$scope.userGroupList2 = result.data.data;
            });
        }else{
            this.userGroupService.getList("", 0, -1).then(result => {
                this.$scope.userGroupList = result.data.data;
            });
        }

       
    }

    /**
     * 加载数据
     */
    loadData(queryTerms: IUserManagentQueryTerms, skip: number, count: number): void {
        this.userService.getList(queryTerms.userName, queryTerms.phoneNumber, queryTerms.isEnabled, queryTerms.userGroupId, skip, count).then(result => {
            this.$scope.gridOptions.totalItems = result.data.total;
            result.data.data.map((item, index) => item.index = skip++ + 1);
            this.$scope.gridOptions.data = result.data.data;

            /**
             * 设置列表高度
             */


            this.$scope.heightA = (this.$scope.gridOptions.data.length * 39) + 95;



            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }

            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }

    /**
     * 填充已选用户组权限
     */
    selectUserGroupAuth = ()=> {
        
        if (this.$scope.detail.userGroupId) {                        
            this.userGroupService.getDetail(this.$scope.detail.userGroupId).then(result => {
                this.$scope.detail.roles.role = result.data.roles;
                // console.log(this.$scope.detail.roles);
            });
        } else {
            this.$scope.detail.roles.role = [];
            console.log(this.$scope.detail.roles);
        }

        var selectedUserGroup = this.$scope.userGroupList2.filter(item=>{
            return item.id===this.$scope.detail.userGroupId
        })[0];
        if(selectedUserGroup){
            this.$scope.detail.highAuthNumber=selectedUserGroup.highAuthNumber;
            this.$scope.detail.middleAuthNumber=selectedUserGroup.middleAuthNumber;
            this.$scope.detail.lowAuthNumber=selectedUserGroup.lowAuthNumber;
            this.$scope.detail.secAuthorizationTypeTag=selectedUserGroup.secAuthorizationTypeTag;
        }
       


    }

    /**
     * 显示添加用户窗口
     */
    // showAddUserDialog = () => {
    //     $("#authorizationCheck").find("input[type='checkbox']").prop("checked", false);
    //     $("#password").addClass("required");
    //     $("#rePassword").addClass("required");

// <<<<<<< HEAD
//         this.$scope.title = "添加用户";
//         this.$scope.detail = {
//             userNameBox: "",
//             password: "",
//             rePassword: "",
//             email: "",
//             phoneNumberBox: "",
//             isEnabledBox: true,
//             userGroupId: "",
//             roles: { role: [] },
//             passwordTitle: "重复密码",
//             click: this.addUser,
//             userGroupSelected: this.selectUserGroupAuth,
//             nameDisable: false
//         };
//     }

    addUser = () => {
        if (!$("#userForm").valid()) { return; }
        this.$ngBootbox.confirm("确定保存此数据吗？").then(e => {
            this.userService.add(
                this.$scope.detail.userNameBox,
                this.$scope.detail.password,
                this.$scope.detail.rePassword,
                this.$scope.detail.email,
                this.$scope.detail.phoneNumberBox,
                this.$scope.detail.isEnabledBox,
                this.$scope.detail.userGroupId,
                this.$scope.detail.roles.role
            ).then((res) => {
                this.reload(this.$scope.gridOptions.paginationCurrentPage);
                $("#myModal").modal("hide");
            })
        })
    }

    /**
     * 显示编辑用户窗口
     */
    showEditUserDialog = (row:any) => {
        var id=row.id
        $("#authorizationRepeat").find("input[name='itemCheckN']").prop("checked", false);
        let validator = $('#userForm').validate();
        validator.form();
        validator.hideErrors();
        $(".error").removeClass("error");
        $('#password').removeClass('required');
        $('#rePassword').removeClass('required');

        this.$scope.title = "编辑用户";
        this.userService.getDetail(id).then(result => {
            this.$scope.detail = {
                id: id,
                userNameBox: result.data.userName,
                password: "",
                rePassword: "",
                email: result.data.email,
                phoneNumberBox: result.data.phoneNumber,
                isEnabledBox: result.data.isEnabled,
                userGroupId: result.data.userGroupId,
                roles: { role: result.data.roles },
                passwordTitle: "重复密码",
                nameDisable: true,
                userGroupSelected: this.selectUserGroupAuth,
                click: this.editUser,
                highAuthNumber:row.highAuthNumber,
                middleAuthNumber:row.middleAuthNumber,
                lowAuthNumber:row.middleAuthNumber,
                secAuthorizationTypeTag:row.secAuthorizationTypeTag
            };
        });

        this.loadUserGroupDropDown(row.logisticsCompanyId);
    }

    editUser = ()=> {
        if(!this.$scope.detail.phoneNumberBox || this.$scope.detail.phoneNumberBox.length!=11){
            this.$ngBootbox.alert('请输入正确的11位手机号');
            return;
        }
        this.$ngBootbox.confirm("确定保存此数据吗").then(() => {
            this.userService.edit(
                this.$scope.detail.id,
                this.$scope.detail.password,
                this.$scope.detail.rePassword,
                this.$scope.detail.email,
                this.$scope.detail.phoneNumberBox,
                this.$scope.detail.isEnabledBox,
                this.$scope.detail.userGroupId,
                this.$scope.detail.roles.role,
                this.$scope.detail.highAuthNumber,
                this.$scope.detail.middleAuthNumber,
                this.$scope.detail.lowAuthNumber,
                this.$scope.detail.secAuthorizationTypeTag
            ).then((res)=> {
                this.reload(this.$scope.gridOptions.paginationCurrentPage);
                $("#myModal").modal("hide");
            });
        });
    }

    /**
    * 编辑用户权限
    */
    editUserAuthorization = (row) => {
        this.$scope.UserName = row.name;
        // console.log(row);
        this.visualAuthorizationService.getList(row.id, null,row.logisticsCompanyId).then(res => {
            this.$scope.authTree = res.data
        })
        this.$scope.treeExpand = false;
        
        this.selectedRow = row;
    }

    saveCheckedAuth = () => {
        // this.$scope.saveChecked++;
        this.$ngBootbox.confirm('确认保存数据吗').then(e => {
            console.log(e)
            // console.log(this.$scope.authNumbers,this.$scope.secAuthTypeTag);
            let checkedNumbers = { high: [], middle: [], low: [] }, secAuthTags = [];

            let nodes = this.$scope.authTree.data;
            nodes && nodes.forEach(firstAuth => {
                firstAuth.secAuthTypeList && firstAuth.secAuthTypeList.forEach(secNode => {
                    secNode.visualAuthList && secNode.visualAuthList.forEach(thNode => {
                        if (thNode.isShow) {
                            // checkedNumbers.push(thNode.authNumber);
                            let key = ['high', 'middle', 'low'][thNode.level - 1];
                            if (key) {

                                // console.log(checkedNumbers);
                                checkedNumbers[key].push(thNode.number);
                            }

                            if (secAuthTags.indexOf(thNode.secAuthorizationTypeTag) === -1) {
                                secAuthTags.push(thNode.secAuthorizationTypeTag);
                            }
                        }
                    })
                })

            })
            this.$scope.authNumbers = checkedNumbers;
            this.$scope.secAuthTypeTag = secAuthTags;
            let authObj = {
                HighAuthNumber: this.$scope.authNumbers.high,
                //中等级权限
                MiddleAuthNumber: this.$scope.authNumbers.middle,
                //低等级权限
                LowAuthNumber: this.$scope.authNumbers.low,
                //二级权限标签
                SecAuthTypeTag: this.$scope.secAuthTypeTag
            }
            this.userService.editAuth(this.selectedRow.id, authObj).then(res => {
                // console.log(res)
                this.reload(this.$scope.gridOptions.paginationCurrentPage);
                $('#authModal').modal('hide');

            })
        })
    }

}

angular.module('tms').controller('userManagentController', ['$scope', 'userService', 'userGroupService', '$ngBootbox', 'visualAuthorizationService', UserManagentController]);